package org.steven.crm.core.service.customer;

import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;
import org.apache.commons.lang3.StringUtils;
import org.steven.crm.core.query.CustomerQueryDataList;
import org.steven.crm.core.service.BaseService;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/6/21 14:38
 * @Version 1.0
 */
public class CustomerService extends BaseService {
    @Override
    protected String getTable() {
        return "customer";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return new CustomerQueryDataList();
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    @Override
    public void beforeCreate(Map<String, String> data) throws Exception {
        super.beforeCreate(data);
        if (isExistsName("", data.get("name"))) {
            throw new Exception("客户名称已存在");
        }
    }

    @Override
    public void beforeUpdate(String id, Map<String, String> data) throws Exception {
        super.beforeUpdate(id, data);
        if (isExistsName(id, data.get("name"))) {
            throw new Exception("客户名称已存在");
        }
    }

    public boolean isExistsName(String id, String name) throws Exception {
        String extendSql = "";
        if (!StringUtils.isEmpty(id)) {
            extendSql = " and id != " + id;
        }
        Map<String, String> key = new HashMap<>();
        key.put("name", name);
        key.put("deleted", "0");

        return DBManager.query(getSession(), getTable(), "*", key, extendSql).size() > 0;
    }

}
